package com.jinyi.wwdeng.ui.main.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.GravityCompat
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.jinyi.base.utils.BarUtils
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.analysis.TestDataLibInvoke
import com.jinyi.wwdeng.databinding.FragmentCreditLimitBinding
import com.jinyi.wwdeng.pro.ProMvpFragment
import com.jinyi.wwdeng.ui.main.act.CreditApplyAct
import com.jinyi.wwdeng.ui.main.contract.CreditLimitContract
import com.jinyi.wwdeng.ui.main.impl.CreditLimitPresenterImpl
import com.jinyi.wwdeng.ui.steps.act.StepListAct
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.ui.user.fragment.UserFragment
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/17 14:34
 * @Annotation：贷款额度
 */
class CreditLimitFragment(var isComplete: Boolean): ProMvpFragment<CreditLimitContract.View, CreditLimitPresenterImpl>(),CreditLimitContract.View {

    lateinit var binding: FragmentCreditLimitBinding

    override fun getRootView(inflater: LayoutInflater): View {
        binding = FragmentCreditLimitBinding.inflate(inflater)
        return binding.root
    }

    override fun createPresenter(): CreditLimitPresenterImpl {
        return CreditLimitPresenterImpl()
    }

    override fun initView() {
        binding.parentLayout.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        binding.tvTitle.text = getString(R.string.app_name)
        initRefreshLayout()

        //添加侧边个人中心
        addMenuFragment()
        showCompleteView()
    }

    override fun initListener() {
        //个人中心
        binding.ivAvatar.setOnClickListener {
            var isOpen = binding.drawerLayout.isDrawerOpen(GravityCompat.START)
            if (isOpen){//是否打开
                binding.drawerLayout.closeDrawer(GravityCompat.START,true)
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER,"CreditLimit Page Close")
            } else {
                binding.drawerLayout.openDrawer(GravityCompat.START,true)
                TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_USER,"CreditLimit Page Open")
            }
        }
        //客服
        binding.ivKefu.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"CreditLimit Page")
        }

        //申请
        binding.btnApply.setOnClickListener {
            //上报
            TestDataLibInvoke.sycData()
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_LIMIT_ADD_INFORMATION,"")

            checkAllPermissions(false)
        }

        //添加个人信息
        binding.includeType1.btnAdd.setOnClickListener {
            binding.btnApply.callOnClick()
        }

        //Check
        binding.includeType2.btnCheck.setOnClickListener {
            //上报
            TestDataLibInvoke.sycData()
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CREDIT_LIMIT_CHECK,"")

            checkAllPermissions(true)
        }
    }

    override fun initData() {
        loadDataAction()
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATE)
            requireContext().sendBroadcast(intent)

            loadDataAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 显示样式
     */
    fun showCompleteView(){
        when(isComplete){
            true -> {//已完成 - 显示额度
                binding.includeType1.informationLayout.visibility = View.GONE
                binding.includeType2.limitLayout.visibility = View.VISIBLE
                binding.tipsLayout.visibility = View.VISIBLE
                binding.btnApply.visibility = View.GONE
            }
            else -> {//未完成 - 显示完善资料
                binding.includeType1.informationLayout.visibility = View.VISIBLE
                binding.includeType2.limitLayout.visibility = View.GONE
                binding.tipsLayout.visibility = View.GONE
                binding.btnApply.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 添加侧边菜单
     */
    private fun addMenuFragment(){
        childFragmentManager
            .beginTransaction()
            .add(R.id.menuLayout, UserFragment(binding.drawerLayout)) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * 加载数据
     */
    private fun loadDataAction(){
        presenter.loadCreditLimitRequest()
        presenter.loadAllPermissionList()
    }

    /**
     * 显示额度
     */
    @SuppressLint("SetTextI18n")
    override fun showCreditLimitData(data: JSONObject) {
        binding.tvAmount.text = data.optString("amount1")
        binding.includeType1.tvSignAmount.text = "+${data.optString("amount2")}"
        binding.includeType1.tvInformationAmount.text = "+${data.optString("amount3")}"

        binding.includeType2.tvLimitAmount.text = data.optString("amount")
    }

    /**
     * 检查是否授权所有权限
     */
    private fun checkAllPermissions(isApply: Boolean){
        if (presenter.isAgreeAll()){
            if (isApply){
                startCreditApply()
            } else {
                startAddInformation()
            }
        } else {
            XXPermissions.with(this)
                // 申请多个权限
                .permission(presenter.getAllPermissionList())
                .request(object: OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                        if (isApply){
                            startCreditApply()
                        } else {
                            startAddInformation()
                        }
                    }
                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                        XXPermissions.startPermissionActivity(context!!,permissions)
                    }
                })
        }
    }

    /**
     * 添加个人信息
     */
    private fun startAddInformation(){
        onIntent(StepListAct::class.java)
    }

    /**
     * 贷款申请页面
     */
    private fun startCreditApply(){
        onIntent(CreditApplyAct::class.java)
    }

    /**
     * 加载完成
     */
    override fun onRequestFinish() {
        hideLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_LIMIT_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_CREDIT_LIMIT_END,"")
    }
}